#监控微信聊天   
from wxauto import WeChat
import time
import os
import threading
import requests
import json

# 直接定义配置
API_CONFIG = {
    "api_key": "sk-9f407fd69c17440682d5dcf16edab91b",
    "api_url": "https://api.deepseek.com/v1/chat/completions",
    "model_name": "deepseek-chat"
}

GENERATION_CONFIG = {
    "max_tokens": 2000,
    "temperature": 0.8,
    "timeout": 60
}

# 初始化微信客户端
wx = WeChat()

# 设置监听的好友名称
TARGET_FRIEND = "杨教主"
AUTO_REPLY = ""


def listen_and_reply():
    print(f"开始监听 [{TARGET_FRIEND}] 的消息...")
    print("请确保微信已登录且聊天窗口已打开")
    last_msg_signature = None  # 记录上一条消息的唯一标识（时间+内容）
    last_process_time = 0  # 记录上次处理消息的时间
    loop_count = 0

    while True:
        try:
            loop_count += 1
            if loop_count % 30 == 0:  # 每30次循环打印一次状态
                print(f"正在监听中...已运行{loop_count}次检查")
            
            # 获取所有消息（返回的是消息对象列表）
            all_msgs = wx.GetAllMessage()
            if not all_msgs:
                time.sleep(3)
                continue

            # 取最后一条消息（现在是 FriendTextMessage 对象）
            last_msg_obj = all_msgs[-1]

            # 从消息对象中提取发送者、消息内容和时间戳
            current_time = time.time()
            if isinstance(last_msg_obj, dict):
                # 如果是字典格式
                sender = last_msg_obj.get('sender', '') or last_msg_obj.get('name', '')
                msg = last_msg_obj.get('content', '') or last_msg_obj.get('msg', '')
                timestamp = last_msg_obj.get('timestamp', current_time)
            else:
                # 如果是对象格式
                sender = getattr(last_msg_obj, 'sender', '') or getattr(last_msg_obj, 'name', '')
                msg = getattr(last_msg_obj, 'content', '') or getattr(last_msg_obj, 'msg', '')
                timestamp = getattr(last_msg_obj, 'timestamp', current_time)

            # 跳过空消息
            if not msg or not msg.strip():
                time.sleep(3)
                continue

            # 创建消息唯一标识（内容+时间戳组合）
            msg_signature = f"{msg}_{int(timestamp)}"
            
            # 检查是否是目标好友的新消息（避免30秒内重复处理相同内容）
            is_new_msg = (
                sender == TARGET_FRIEND and 
                msg_signature != last_msg_signature and 
                current_time - last_process_time > 30  # 30秒内不重复处理
            )
            
            if is_new_msg:
                print(f"收到新消息: {msg}")
                # 调用大模型生成智能回复
                ai_reply = get_ai_response(msg)
                wx.SendMsg(ai_reply)
                print(f"已回复: {ai_reply}")
                last_msg_signature = msg_signature
                last_process_time = current_time

        except AttributeError as e:
            print(f"属性错误: {e}")
            print("请检查wxauto库版本或微信版本是否兼容")
            time.sleep(3)
        except Exception as e:
            print(f"发生错误: {e}")
            print("请确保：")
            print("1. 微信已登录")
            print("2. 微信窗口未最小化")
            print("3. 目标好友的聊天窗口已打开")
            time.sleep(2)


def get_ai_response(user_message):
    """调用大模型API生成智能回复"""
    try:
        headers = {
            'Content-Type': 'application/json',
            'Authorization': f'Bearer {API_CONFIG["api_key"]}'
        }
        
        data = {
            "model": API_CONFIG["model_name"],
            "messages": [
                {"role": "user", "content": user_message}
            ],
            "max_tokens": GENERATION_CONFIG["max_tokens"],
            "temperature": GENERATION_CONFIG["temperature"]
        }
        
        response = requests.post(
            API_CONFIG["api_url"],
            headers=headers,
            json=data,
            timeout=GENERATION_CONFIG["timeout"]
        )
        
        if response.status_code == 200:
            result = response.json()
            return result['choices'][0]['message']['content'].strip()
        else:
            return "抱歉，我现在无法回复，请稍后再试~"
            
    except Exception as e:
        print(f"调用AI回复出错: {e}")
        return "宝贝，我在忙工作，稍后回复你哦~❤️"

def clear_log_periodically():
    """每5分钟清理一次日志文件"""
    log_path = "wxauto_logs/app_20250726.log"
    while True:
        time.sleep(300)  # 5分钟 = 300秒
        try:
            if os.path.exists(log_path):
                with open(log_path, 'w', encoding='utf-8') as f:
                    f.truncate()  # 清空文件内容
                print(f"已清理日志文件: {log_path}")
        except Exception as e:
            print(f"清理日志文件时出错: {e}")

if __name__ == "__main__":
    # 启动日志清理线程
    cleanup_thread = threading.Thread(target=clear_log_periodically, daemon=True)
    cleanup_thread.start()
    
    # 启动主监听程序
    listen_and_reply()